var User = require('../models/user');
var Post = require('../models/post');
var Comment = require('../models/comment');
var crypto = require('crypto');
var multer = require('multer');
var upload = require('../models/upload');
/*var storage = multer.diskStorage({
    destination:function(req,file,res,cb){
        cb(null,'public/images')
        console.log(res);
    },
    filename:function(req,file,res,cb){
        cb(null,file.originalname)
    }
});
var upload = multer({storage:storage,size:10225});*/


function checkLogin(req, res, next) {
    if (!req.session.user) {
        req.flash('error', '未登录!');
        res.redirect('/login');
    }
    next();
}
function checkNotLogin(req, res, next) {
    if (req.session.user) {
        req.flash('error', '已登录!');
        res.redirect('back');
    }
    next();
}
module.exports = function(app){
    //首页
    app.get('/',function(req,res){
        var page = parseInt(req.query.p) || 1;
        Post.getTen(null,page,function(err,posts,total,docs){
            if(err){
                posts = [];
            }
            res.render('index',{
                user:req.session.user,
                page:page,
                posts:posts,
                isFirstPage: (page - 1) == 0,
                isLastPage: (page - 1) * 10 + posts.length == total,
                pageNum: Math.ceil(total / 10),
                success:req.flash('success').toString(),
                error:req.flash('error').toString(),
                content:docs
            })
        })

    });
    //注册页面
    app.get('/reg', checkNotLogin);
    app.get('/reg',function(req,res){
        res.render('reg',{
            user:req.session.user,
            success:req.flash('success').toString(),
            error:req.flash('error').toString()
        })
    });
    //注册行为
    app.post('/reg', checkNotLogin);
    app.post('/reg',function(req,res){
        var name = req.body.name;
        //密码
        var password = req.body.password;
        //确认密码
        var password_re = req.body['password-repeat'];
        //邮箱
        var email = req.body.email;
        //补充一下，如果未填写的情况下，提示用户
        if(name == '' || password == '' || password_re == '' || email == ''){
            req.flash('error','请正确填写信息');
            return res.redirect('/reg');
        }
        //检查两次密码是否一样
        if(password_re != password){
            //先保存一下当前的错误信息
            req.flash('error','用户两次输入的密码不一样');
            return res.redirect('/reg');
        }
        //对密码进行加密处理
        var md5 = crypto.createHash('md5');
        var password = md5.update(req.body.password).digest('hex');
        //console.log(password);

        //实例化User对象了
        var newUser = new User({
            name:name,
            password:password,
            email:email
        });
        //检查用户名是否存在
        User.get(newUser.name,function(err,user){
            //发生错误,跳转回首页
            if(err){
                req.flash('error',err);
                return res.redirect('/');
            }
            //如果存在重复的用户名
            if(user){
                req.flash('error','用户名已经存在');
                return res.redirect('/reg');
            }
            //正确情况下
            newUser.save(function(err,user){
                if(err){
                    req.flash('error',err);
                }
                //用户信息存入session
                req.session.user = newUser;
                req.flash('success','注册成功');
                res.redirect('/');
            })
        })
    });
    //登录
    app.get('/login', checkNotLogin);
    app.get('/login',function(req,res){
        res.render('login',{
            user:req.session.user,
            success:req.flash('success').toString(),
            error:req.flash('error').toString()
        })
    });
    //登录行为
    app.post('/login', checkNotLogin);
    app.post('/login',function(req,res){
        var md5 = crypto.createHash('md5');
        var password = md5.update(req.body.password).digest('hex');
        User.get(req.body.name,function(err,user){
            if(!user){
                //说明用户名不存在
                req.flash('error','用户名不存在');
                return res.redirect('/login');
            }
            //检查两次密码是否一样
            if(user.password != password){
                req.flash('error','密码错误');
                return res.redirect('/login');
            }
            req.session.user = user;
            //console.log(req.session.user);
            req.flash('success','登录成功');
            res.redirect('/');
        })

    });
    //发表
    app.get('/post', checkLogin);
    app.get('/post',function(req,res){
        res.render('post',{
            user:req.session.user,
            success:req.flash('success').toString(),
            error:req.flash('error').toString()
        })
    });
    //发表行为
    app.post('/post', checkLogin);
    app.post('/post',function(req,res){
        //当前SESSION里面的用户信息
        var currentUser = req.session.user;
        //判断一下内容不能为空
        if(req.body.title == '' || req.body.post == ''){
            req.flash('error','内容不能为空');
            return res.redirect('/post');
        }
        //添加一下标签信息
        var tags = [req.body.tag1];
        var post = new Post(currentUser.name,req.body.title,tags,req.body.post,req.session.user.txname);
        post.save(function(err){
            if(err){
                req.flash('error',err);
                return res.redirect('/');
            }
            req.flash('success','发布成功');
            res.redirect('/');
        })
    });
    //上传
    app.get('/upload',checkLogin,function (req,res) {
        //console.log(req.session.user);
        res.render('upload',{
            user:req.session.user,
            success:req.flash('success').toString(),
            error:req.flash('error').toString()
        })
    });
    app.post('/upload',upload.single('photo'),function (req,res) {
        //console.log(req.extension);//头像文件名
        if(req.file){
            User.insert(req.session.user.name,req.extension,function(err,user){
                //如果发生了错误,跳转回首页
                if(err){
                    req.flash('error',err);
                    return res.redirect('/upload');
                }
                req.session.user = user;
                req.flash('success','头像上传成功');
                res.redirect('/upload');
            });
        }else{
            req.flash('error','请选择头像！');
            res.redirect('/upload');
        }
    })
    /*app.get('/upload',checkLogin);
    app.get('/upload',function(req,res){
        res.render('upload',{
            user:req.session.user,
            success:req.flash('success').toString(),
            error:req.flash('error').toString()
        })
    })*/
    //上传行为
    /*app.post('/upload',checkLogin);
    app.post('/upload',upload.array('field1',5),function(req,res){
        req.flash('success','文件保存成功');
        res.redirect('/upload');
    })*/
    //退出
    app.get('/logout',function(req,res){
        //1.清除session
        //2.给用户提示
        //3.跳转到首页
        req.session.user = null;
        req.flash('success','成功退出');
        res.redirect('/');
    })
    //点击用户名，可以看到用户发布的所有文章
    app.get('/u/:name', function (req, res) {
        var page = parseInt(req.query.p) || 1;
        //检查用户是否存在
        User.get(req.params.name, function (err, user) {
            if (!user) {
                req.flash('error', '用户不存在!');
                return res.redirect('/');
            }
            //查询并返回该用户第 page 页的 10 篇文章
            Post.getTen(user.name, page, function (err, posts, total) {
                if (err) {
                    req.flash('error', err);
                    return res.redirect('/');
                }
                res.render('user', {
                    title: user.name,
                    posts: posts,
                    page: page,
                    isFirstPage: (page - 1) == 0,
                    isLastPage: ((page - 1) * 10 + posts.length) == total,
                    pageNum: Math.ceil(total / 10),
                    user: req.session.user,
                    success: req.flash('success').toString(),
                    error: req.flash('error').toString()
                });
            });
        });
    });
    //文章详情页面
    app.get('/u/:name/:minute/:title',function(req,res){
        Post.getOne(req.params.name,req.params.minute,req.params.title,function (err,post,docs) {
            if(err){
                req.flash('error','找不到当前文章');
                return res.redirect('/');
            }
            res.render('article',{
                title:req.params.title,
                user:req.session.user,
                post:post,
                success:req.flash('success').toString(),
                error:req.flash('error').toString(),
                content:docs
            })
        })
    });
    //文章的留言发布
    app.post('/comment/:name/:minute/:title',function(req,res){
        var date = new Date();
        var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +
            date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
        var comment = {
            name:req.body.name,
            time:time,
            content:req.body.content
        };
        console.log(comment)
        var newCommnet = new Comment(req.params.name,req.params.minute,req.params.title,comment);
        newCommnet.save(function(err){
            if(err){
                req.flash('error',err);
                return res.redirect('back');
            }
            req.flash('success','发布成功');
            res.redirect('back');

        })
    });
    //文章编辑
    app.get('/edit/:name/:minute/:title',checkLogin);
    app.get('/edit/:name/:minute/:title',function(req,res){
        //获取到当前的用户
        var currentUser = req.session.user;
        Post.edit(currentUser.name,req.params.minute,req.params.title,function(err,post){
            if(err){
                req.flash('error',err);
                return res.redirect('back');
            }
            res.render('edit',{
                user:req.session.user,
                post:post,
                success:req.flash('success').toString(),
                error:req.flash('error').toString()
            })
        })
    });
    //文章编辑行为
    app.post('/edit/:name/:minute/:title',checkLogin);
    app.post('/edit/:name/:minute/:title',function(req,res){
        Post.update(req.params.name,req.params.minute,req.params.title,
            req.body.post,function(err){
                //encodeURI是防止有中文的情况下，对中文的字符进行转义
                var url = encodeURI('/u/'+ req.params.name + '/' + req.params.minute + '/' + req.params.title);
                if(err){
                    req.flash('error',err);
                    return res.redirect(url);
                }
                req.flash('success','编辑成功');
                return res.redirect(url);
        })
    });
    //文章删除行为
    app.get('/remove/:name/:minute/:title',checkLogin);
    app.get('/remove/:name/:minute/:title',function(req,res){
        Post.remove(req.params.name,req.params.minute,req.params.title,function(err){
            if(err){
                req.flash('error',err);
                return res.redirect('back');
            }
            req.flash('success','修改成功');
            res.redirect('/');
        })
    });
    //朋友圈
    app.get('/friends',function(req,res){
        var page = parseInt(req.query.p) || 1;
        Post.getTen(null,page,function(err,posts,total,docs){
            if(err){
                posts = [];
            }
            res.render('friends',{
                user:req.session.user,
                page:page,
                posts:posts,
                isFirstPage: (page - 1) == 0,
                isLastPage: (page - 1) * 10 + posts.length == total,
                pageNum: Math.ceil(total / 10),
                success:req.flash('success').toString(),
                error:req.flash('error').toString(),
                content:docs
            })
        })

    });
    //文章标签页
    app.get('/tags',function(req,res){
        Post.getTags(function(err,posts){
            if(err){
                req.flash('error',err);
                res.redirect('/');
            }
            res.render('tags',{
                posts:posts,
                user:req.session.user,
                success:req.flash('success').toString(),
                error:req.flash('error').toString()
            })
        })
    });
    //标签对应的文章集合
    app.get('/tags/:tag',function(req,res){
        Post.getTag(req.params.tag,function(err,posts){
            if(err){
                req.flash('error',err);
                return res.redirect('/');
            }
            res.render('tag',{
                title:'TAG:' + req.params.tag,
                user:req.session.user,
                posts:posts,
                success:req.flash('success').toString(),
                error:req.flash('error').toString()
            })
        })
    });
    app.get('/lhd',function(req,res){
        return res.render('lhd',{
            user:req.session.user,
            success:req.flash('success').toString(),
            error:req.flash('error').toString()
        })
    })
};